<template>
	<el-dialog
        v-model="visible"
        :title="!dataForm.id ? '新增' : '修改'"
        :close-on-click-modal="false"
        draggable>
		<el-form
            ref="dataFormRef"
            :model="dataForm"
            :rules="dataRules"
            label-width="120px"
            @keyup.enter="onSubmit()">
			<el-form-item
                prop="name"
                label="名称"
                class="org-name">
				<el-input
                    v-model="dataForm.name"
                    placeholder="名称">
                </el-input>
			</el-form-item>
			<el-form-item
                prop="parentName"
                label="上级机构"
                class="org-list">
				<el-popover
                    ref="orgListPopover"
                    placement="bottom-start"
                    trigger="click"
                    :width="250"
                    popper-class="popover-pop">
					<template #reference>
						<el-input
                            v-model="dataForm.parentName"
                            :readonly="true"
                            placeholder="上级机构">
							<template #suffix>
								<svg-icon
                                    v-if="dataForm.pid !== 0"
                                    icon="icon-close-circle"
                                    @click.stop="treeSetDate()">
                                </svg-icon>
							</template>
						</el-input>
					</template>
					<div class="popover-pop-body">
						<el-tree
							ref="orgListTree"
							:data="orgList"
							:props="{ label: 'name', children: 'children' }"
							node-key="id"
							:highlight-current="true"
							:expand-on-click-node="false"
							accordion
							@current-change="onTreeChange"
						>
						</el-tree>
					</div>
				</el-popover>
			</el-form-item>
			<el-form-item
                prop="sort"
                label="排序">
				<el-input-number
                    v-model="dataForm.sort"
                    controls-position="right"
                    :min="0"
                    label="排序">
                </el-input-number>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="onSubmit()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import { orgStore } from '@/store/org'
import { storeToRefs } from 'pinia'
// import { SvgIcon } from '@/components/svg-icon/index.vue'

const emit = defineEmits(['refresh'])
const useOrgStore = orgStore()
const { orgList } = storeToRefs(useOrgStore) // 使用storeToRefs解构
const visible = ref(false) // 弹窗是否显示
const dataForm = reactive({
	id: 0, // 主键ID
	name: '', // 名称
	parentName: '', // 上级机构名称
	pid: 0, // 上级机构ID
	sort: 0 // 排序 
})

const dataFormRef = ref(null) // 表单引用
const orgListPopover = ref(null) // 机构列表弹框
const orgListTree = ref(null) // 机构列表树

const init = async (id) => {
    visible.value = true

	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	} 
    if (id) {
        // 修改模式
        try {
            const res = await useOrgStore.getOrgOne(id)
            Object.assign(dataForm, res)

            if (dataForm.pid == 0) {
            	return treeSetDate()
            }

			orgListTree.value.setCurrentKey(dataForm.pid)
        } catch (error) {
            ElMessage.error(error.message || '获取数据失败')
        }
    } else {
        // 新增模式
        dataForm.id = 0
        dataForm.name = ''
        dataForm.parentName = ''
        dataForm.pid = 0
        dataForm.sort = 0
		treeSetDate() // 初始化
    }
	// 这里的下拉菜单中的orgList是从store中获取的好呢，还是从接口中获取的好呢？
}

const dataRules = {
	name: [
		{ required: true, message: '请输入名称', trigger: 'blur' }
	],
	parentName: [
		{ required: true, message: '请选择上级机构', trigger: 'blur' }
	],
}

const onSubmit = async() => {
	if (!dataFormRef.value) return
	await dataFormRef.value.validate(async(valid) => {
		if (valid) {
			try {
				await useOrgStore.saveOrg(dataForm)
				ElMessage.success('操作成功')
				visible.value = false // 关闭弹窗
				emit('refresh') // 刷新列表
			} catch (error) {
				ElMessage.error(error.message || '操作失败')
			}
		} else {
			ElMessage.error('请输入正确的信息')
		}
	})
}

const treeSetDate = () => {
  dataForm.pid = 0
  dataForm.parentName = '一级机构'
}

const onTreeChange = (data) => {
	dataForm.parentName = data.name
	dataForm.pid = data.id
	orgListPopover.value.hide() // 隐藏弹框
}

defineExpose({ init })
</script>

<style lang="scss" scoped>
.org-name {
    :v-deep(.el-input) {
        width: 80%;
    }
}
.org-list {
    :v-deep(.el-input) {
        width: 80%;
    }
	:v-deep(.el-input__inner) {
		cursor: pointer;
	}
}
.popover-pop {
    :v-deep(.el-popper__arrow) {
        left: 0 !important;
        margin-left: 0 !important;
        transform: none !important;
    }
    :v-deep(.el-popper) {
        margin-left: -12px !important;
    }
}
</style>